<template>
  <div class="mainStyle mainStyle-2" v-loading="waitLoading">
    <div class="contentLeft">
      <div class="bottomTree">
        <!-- 目录树 -->
        <treeItem @node-click="nodeClick" @node-delete="nodeDelete" ref="myTreeItem"></treeItem>
      </div>

      <oneClickQuery @call-parent="previewPdf" v-if="role === 'admin'"></oneClickQuery>
      <fileLoading @call-parent="previewPdf"></fileLoading>
    </div>

    <!-- 文件列表 -->
    <!-- 文件名检索 -->
    <div class="contentContainer">
      <div class="contentRight-2 centerFlex" v-if="role === 'admin'">
        <div class="alert-container">
          <el-alert type="error" style="margin-bottom: 10px"
            >1. 如果doc/xls/ppt解析失败，请转换为docx/xlsx/pptx文件再重新上传。</el-alert
          >
          <el-alert type="error"
            >2. 为观察文件上传及解析的实时进度，过程中请尽量不要切换到本站的其它页面。</el-alert
          >
        </div>
        <!-- <el-button type="primary" :disabled="!slected.name" @click="uploadFile('单个上传')"
          ><svg-icon iconClass="upload" style="margin-right: 2px"></svg-icon>文件上传</el-button
        >
        <el-button type="primary" :disabled="!slected.name" @click="uploadFile('单个上传')"
          ><svg-icon iconClass="upload" style="margin-right: 2px"></svg-icon>大文件上传</el-button
        > -->
        <div class="alert-container">
          <el-button
            type="primary"
            class="btn"
            size="medium"
            :disabled="!slected.name"
            @click="upload"
            ><svg-icon iconClass="upload" style="margin-right: 2px"></svg-icon>文件上传</el-button
          >
        </div>
      </div>
      <!-- <bigFileUploaderVue></bigFileUploaderVue> -->
      <div class="contentRight-2">
        <!-- {{ showLoadingList }} -->
        <div class="page-title">当前目录:{{ slected.name }}</div>

        <el-input
          class="search-inp"
          v-model="chatInput"
          clearable
          placeholder="请输入检索内容"
          size="small"
        ></el-input>

        <el-button size="small" type="primary" @click="seachTextFile()">检索</el-button>
        <div class="loading-contaienr">
          <p v-for="item in showLoadingList">
            <el-tag class="loading-item">{{ item.text }}</el-tag>
          </p>
        </div>
        <ul class="file-ul" v-if="!showSearch">
          <li v-for="(item, index) in currentFileList" :key="item.file_id">
            <span class="text-line" @click="previewPdf(item.id, 'file', item.name)"
              >{{ index + 1 }}、{{ item.name }}</span
            >

            <span
              class="fl-btn"
              size="small"
              type="danger"
              v-if="role === 'admin'"
              @click="deleteFile(item)"
              >删除</span
            >

            <el-tag
              style="margin-left: 10px"
              size="small"
              @click="merge(item)"
              type="danger"
              v-if="!item.is_processed"
              >解析文件</el-tag
            >
          </li>
          <li v-if="currentFileList.length === 0">暂无内容</li>
        </ul>
        <ul class="file-ul" v-if="showSearch">
          <li v-for="(item, index) in searchFileList" :key="item.id">
            <span class="text-line" @click="previewPdf(item.id, item.type, item.name)"
              >{{ index + 1 }}、{{ item.name }}</span
            >
            <span
              class="fl-btn"
              size="small"
              type="danger"
              v-if="role === 'admin'"
              @click="deleteFile(item)"
              >删除</span
            >
            <el-tag v-if="!item.is_processed">解析文件</el-tag>
          </li>
        </ul>
      </div>
    </div>
    <el-dialog
      width="40%"
      class="warn-detail-bg"
      title="文件上传"
      :visible.sync="uploadShow"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      @close="uploadShow = false"
    >
      <div class="headerIcon">
        <svg-icon iconClass="upload"></svg-icon>
      </div>
      <div
        class="fault-dialog-body"
        v-loading="loading"
        element-loading-text="上传中,请耐心等待..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.3)"
      >
        <p>请上传.ppt .pptx .xls .xlsx .csv .txt .doc .docx .pdf .md文件</p>
        <el-upload
          class="upload-demo"
          drag
          :multiple="true"
          :limit="30"
          :headers="headers"
          ref="fileUpload"
          accept=".ppt,.pptx,.xls,.xlsx,.csv,.txt,.doc,.docx,.pdf,.md"
          :action="uploadParams.uploadUrl"
          :data="uploadParams.data"
          :file-list="uploadParams.fileLists"
          :on-success="handleSuc"
          :on-error="handleError"
          :auto-upload="false"
          :on-exceed="handleExceed"
          :on-change="changeFile"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="confirm-btn" @click="closeUpload">取 消</el-button>
          <el-button type="primary" @click="uploadForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      top="10px"
      width="60%"
      class="warn-detail-bg"
      title="文件预览"
      :before-close="handleClickDialog"
      :visible.sync="preShow"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
    >
      <div class="markBg">
        <pdfPreview :key="pdfUrl" v-if="typeValue == 1" :pdfUrl="pdfUrl"></pdfPreview>
        <div class="mdbox" v-if="typeValue == 2">
          <div ref="mdViewer" class="mdviewer" :key="keyValue" v-html="markdownContent"></div>
        </div>
        <div class="imgviewer" v-if="typeValue == 3">
          <img :src="imageUrl" alt="" />
        </div>
        <div v-if="typeValue == 4">
          <xg-item
            :deviceObj="{
              url: flvUrl,
              camera_region: '123',
            }"
          ></xg-item>
        </div>
        <vue-office-doc v-if="typeValue == 5" :src="src"></vue-office-doc>
        <vue-office-excel v-if="typeValue == 6" :src="src"></vue-office-excel>
        <vue-office-pdf v-if="typeValue == 7" :src="src"></vue-office-pdf>
        <vue-office-pptx v-if="typeValue == 8" :src="src"></vue-office-pptx>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="confirm-btn" @click="handleClickDialog">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      top="10px"
      width="60%"
      class="warn-detail-bg"
      title="一键上传"
      :visible.sync="uploadDialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
    >
      <div>
        <h2 class="h2-item">请输入问题</h2>
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 6 }"
          v-model="form.question"
        ></el-input>

        <h2 class="h2-item">请输入答案</h2>
        <el-input
          type="textarea"
          :autosize="{ minRows: 7, maxRows: 10 }"
          v-model="form.answer"
        ></el-input>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="confirm-btn" type="primary" @click="uploadAnswer">确 定</el-button>
          <el-button class="confirm-btn" @click="uploadDialog = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getData, postData, deleteData } from '@/service/getData';
import baseUrl from '../../service/env.js';
import { fetchEventSource } from '@microsoft/fetch-event-source';
import axios from 'axios';
import marked from 'marked';
import oneClickQuery from '@/components/oneClickQuery.vue';
import fileLoading from '@/components/fileLoading.vue';

import Player from 'xgplayer';
import 'xgplayer/dist/index.min.css';

import xgItem from '@/components/xgPlayerItem.vue';
import treeItem from '@/components/tree-item.vue';

import { LineBasicMaterial } from 'three';
// import bigFileUploaderVue from '@/components/big-file-uploader.vue';
import Bus from '../../components/vue-simple-uploader/js/bus';
import vueOfficeDoc from '../../components/vue-office-doc.vue';
import vueOfficePdf from '../../components/vue-office-pdf.vue';
import vueOfficeExcel from '../../components/vue-office-excel.vue';
import vueOfficePptx from '../../components/vue-office-pptx.vue';

const blob2Base64 = (blob) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};
export default {
  components: {
    xgItem,
    oneClickQuery,
    treeItem,
    vueOfficeDoc,
    vueOfficePdf,
    vueOfficeExcel,
    vueOfficePptx,
    fileLoading,
  },
  data() {
    return {
      // 选中的目录
      slected: {
        id: '',
        name: '',
      },
      src: '',
      roleDialog: true,
      versionType: process.env.VUE_APP_BASE_API,
      headers: {
        Authorization: '',
      },
      showLoadingList: [],
      role: 'user', // admin
      loading: false,
      waitLoading: false,
      typeValue: '',
      uploadParams: {
        uploadUrl: '/api/knowledge_base/files/',
        data: {},
        name: 'file',
        fileLists: [],
      },
      // 导入-弹框
      uploadShow: false,
      uploadShow2: false,
      flvUrl: '',
      preShow: false,
      addShow: false,
      treeData: [],
      treeDataList: [],
      levelOneSel: '文档知识库', // 一级目录 废弃
      levelTwoSel: 'test',
      treeForm: {
        name: '',
      },
      currentFileList: [],
      searchFileList: [],
      currIndex: '',
      addIndex: '',
      chatInput: '',
      showSearch: false,
      uploadDialog: false,
      uploadDialog2: false,
      limitFileList: [
        {
          name: '市场',
          role: [
            '周百夷',
            '李京姝',
            '超级管理员1',
            '王建坤',
            '王进才',
            '王伟-山东交控',
            '张明静',
            '周大鹏',
            '张志政',
            '毕明荣',
            '高凯',
            '郭恒铭',
            '谷宇',
            '黄超',
            '黄健',
            '金江',
            '梁材国',
            '李春明',
            '麻吉泉',
            '谭剑雪',
          ],
        },
      ],
      saveSelect: [],
      selectList: [],
      litmitArr: [],
      is_parse: true,
      saveLoadName: '',
      form: {
        question: '',
        answer: '',
        collection_name: '文档知识库',
        partition_name: '问答对',
      },
      videoData: null,
      uploadType: '单个上传',
    };
  },
  mounted() {
    // 根据用户权限 判断是否隐藏
    if (this.$store.state.user.groups[0]) {
      switch (this.$store.state.user.groups[0].name) {
        case '超级管理员':
          this.role = 'admin';
          break;
        case '管理员':
          this.role = 'admin';
          break;
        default:
          this.role = 'user';
          break;
      }
    }
    let token = localStorage.getItem('token');
    this.headers['Authorization'] = 'Token ' + token;
    // 文件选择后的回调
    Bus.$on('fileAdded', () => {
      console.log('文件已选择');
    });

    // 文件上传成功的回调
    Bus.$on('fileSuccess', (params) => {
      console.log('文件上传成功!!!!', params);
      if (params) {
        this.merge(params);
      }
      // this.uploadTree();
    });
  },
  beforeDestroy() {
    Bus.$off('fileAdded');
    Bus.$off('fileSuccess');
  },
  methods: {
    uploadTree() {
      this.$refs.myTreeItem.getTree();
      // if (this.role === 'admin') {
      //   this.$refs.myTreeItem.getTree2();
      // } else {
      //   this.$refs.myTreeItem.getTree();
      // }
    },
    upload() {
      let str = 'Token ' + localStorage.getItem('token');
      // alert(str);
      // 打开文件选择框
      Bus.$emit('openUploader', {
        // 给服务端的额外参数
        params: {
          page: 'home',
          // 将文件夹id传递
          folder_id: this.slected.id,
          Authorization: str,
        },
      });
    },
    nodeDelete() {
      this.currentFileList = [];
      this.slected.name = '';
      this.slected.id = '';
      this.seachTextFile();
    },
    nodeClick(obj) {
      this.currentFileList = obj.files;
      this.slected.name = obj.name;
      this.slected.id = obj.id;
      this.seachTextFile();
    },
    limitFile(value) {
      let returnValue = true;
      this.limitFileList.forEach((item) => {
        if (item.name === value) {
          // 判断数组中是否包含当前用户的名字 有就显示 没有就不显示
          if (!item.role.includes(this.$store.state.user.username)) {
            returnValue = false;
          }
        }
      });
      return returnValue;
    },
    merge(obj) {
      this.$message.success('开始解析文件，请耐心等待...');
      // 解析文件
      var _this = this;
      const controller = new AbortController();
      fetchEventSource('api/knowledge_base/files/parse_file_sse/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          Accept: ['text/event-stream', 'application/json'],
          Authorization: this.headers['Authorization'],
        },

        body: JSON.stringify({
          file_id: obj.id,
        }),
        openWhenHidden: true,
        signal: controller.signal, //与其相关联的signal属性
        onopen(e) {
          console.log(e, 'SSE在连接打开时被调用');
          if (e.status === 503) {
            _this.$message.error('文件已解析完成, 不能重新解析');
          } else if (e.status === 409) {
            _this.$message.error('文件正在解析, 请等待');
          }
          // 判断 showLoadingList 中是否存在 task_id  如果存在 就不添加
        },
        onmessage(msg, event) {
          const jsonStr = msg.data;
          console.log(msg, event);
          const taskObj = JSON.parse(jsonStr);
          if (msg.event === 'completed') {
            _this.showLoadingList.forEach((item, index) => {
              if (item.id == taskObj.task_id) {
                _this.showLoadingList.splice(index, 1);
                _this.uploadTree();
                _this.$message.success('文件解析成功');
                controller.abort();
              }
            });
          } else if (msg.event === 'error') {
            _this.showLoadingList.forEach((item, index) => {
              if (item.id == taskObj.task_id) {
                _this.showLoadingList.splice(index, 1);
                _this.uploadTree();
                _this.$message.error('文件解析失败');
                controller.abort();
              }
            });
          } else if (msg.event === 'waiting') {
            // 查询是否存在当前任务 如果不存在 则新建一个 存在则更新状态
            let isExist = _this.showLoadingList.some((item) => {
              return item.id == taskObj.task_id;
            });
            if (isExist) {
              // 通过ID 更新状态
              _this.showLoadingList.forEach((item, index) => {
                if (item.id == taskObj.task_id) {
                  item.name = taskObj.file_name; //
                  item.text = taskObj.message;
                }
              });
            } else {
              _this.showLoadingList.push({
                id: taskObj.task_id,
                name: '',
                text: obj.name + ' 开始解析中...',
              });
            }
          }
        },
        onclose(e) {
          console.log('onclose', e);
          controller.abort();
        },
        onerror(err) {
          console.log('onerror:', err);
          controller.abort();
          // _this.$message.error("出错了,请稍后刷新重试3");
        },
      });
    },
    handleClickDialog() {
      this.preShow = false;
      this.typeValue = '';
    },
    longUpload(str, arr) {
      this.litmitArr = [''];
      arr.forEach((item) => {
        this.litmitArr.push(item.partition_name);
      });
      // 需要屏蔽的 内容
      this.saveLoadName = str;
      this.saveSelect = [];
      this.uploadDialog2 = true;
      // 获取内容
      postData(
        '/get_disk_partitions',
        {
          collection_name: this.saveLoadName,
        },
        'post',
        {
          headers: { 'Content-Type': 'application/json;charset=UTF-8', Cookie: '' },
        },
      )
        .then((res) => {
          // 获取选项 并赋值
          this.selectList = [];
          res.contents.forEach((item) => {
            if (this.litmitArr.includes(item)) {
              this.selectList.push({
                value: item,
                disabled: true,
              });
            } else {
              this.selectList.push({
                value: item,
                disabled: false,
              });
            }
          });
        })
        .finally(() => {});
    },

    openupload() {
      this.uploadDialog = true;
    },
    uploadAnswer() {
      postData(
        '/add_qa_pairs',
        {
          ...this.form,
        },
        'post',
        {
          headers: { 'Content-Type': 'application/json;charset=UTF-8', Cookie: '' },
        },
      )
        .then((res) => {
          this.uploadDialog = false;
          this.form.question = '';
          this.form.answer = '';
          this.$message.success('上传成功');
        })
        .finally(() => {});
    },

    // 获取视频流地址
    getVideoRUrl2(str) {
      this.$message.info('努力加载中，请稍侯...');
      const formData = new FormData();
      formData.append('video_id', str);
      // 发送参数为formData的post请求

      axios
        .post('/preview_video', formData, { responseType: 'blob' })
        .then((res) => {
          this.preShow = true;
          // // 加载视频
          this.typeValue = 4;

          let videoData = res.data;
          let blob = new Blob([videoData], { type: 'video/mp4' });
          const blobURL = URL.createObjectURL(blob);
          this.flvUrl = blobURL;

          // this.flvUrl = '/live' + arr[1];
          // this.videoData =res.data
        })
        .catch((e) => {
          this.$message.error('获取文件失败，请稍后重试或联系管理员...');
        });
    },
    getVideoRUrl(str, id) {
      this.$message.info('努力加载中，请稍侯...');
      const formData = new FormData();
      formData.append('video_id', str);
      // 发送参数为formData的post请求

      postData('api/knowledge_base/files/preview_file/', { file_id: str }, 'post', {
        responseType: 'blob',
      })
        .then((res) => {
          this.preShow = true;
          // // 加载视频
          this.typeValue = 4;

          let blob = new Blob([res], { type: 'video/mp4' });
          const blobURL = URL.createObjectURL(blob);
          this.flvUrl = blobURL;

          // this.flvUrl = '/live' + arr[1];
          // this.videoData =res.data
        })
        .catch((e) => {
          this.$message.error('获取文件失败，请稍后重试或联系管理员...');
        });
    },
    //确定上传
    uploadForm() {
      this.$refs.fileUpload.submit();
    },
    closeUpload() {
      this.loading = false;
      this.uploadShow = false;
      this.$refs.fileUpload.abort();
      this.$message.warning('取消上传');
    },
    changeFile(file, fileList) {
      console.log(file, fileList, 'changeFile');
      this.uploadParams.fileLists = fileList;
      this.uploadParams.data = {
        folder_id: this.slected.id,
      };
    },
    //上传文件弹窗
    uploadFile(type) {
      this.uploadType = type;
      // 根据一级目录判断 上传地址 如果 是 多媒体库 就调用 upload_多媒体库 接口
      console.log(this.levelOneSel, this.levelTwoSel, this.uploadParams.uploadUrl);
      if (this.levelOneSel === '多媒体库') {
        this.uploadParams.uploadUrl = '/upload_multimedia';
      } else {
        this.uploadParams.uploadUrl = '/api/knowledge_base/files/';
      }
      this.uploadParams.data = {
        folder_id: this.slected.id,
      };
      this.$set(this.uploadParams, 'fileLists', []);
      this.$forceUpdate();
      this.uploadShow = true;
    },

    // 关闭文件上传窗口
    beforeClose() {
      // debugger
      this.loading = false;
      this.uploadShow = false;
      this.$set(this.uploadParams, 'fileLists', []);
      this.$forceUpdate();
    },
    handleExceed(files, fileList) {
      this.$message.warning('超出5个文件，请重新上传数量');
      return false;
    },
    handleError(err, file, fileList) {
      if (err.status == 409) {
        // 上传失败处理
        this.$message({
          message: '文件已存在，请勿重复上传。',
          type: 'warning',
        });
      } else if (err.status == 504) {
        // 上传失败处理
        this.$message({
          message: '文件较大，后台处理中，稍后请刷新查看。',
          type: 'warning',
        });
      } else {
        // 上传失败处理
        this.$message({
          message: '上传失败，请重新上传文件或联系管理员' /*  */,
          type: 'error',
        });
      }
      this.beforeClose();
    },
    /**
     * @description: 文件上传成功时的钩子
     * @param {object} res 后端的返回数据
     * @return:
     */
    handleSuc(res, file, fileList) {
      var _this = this;
      this.uploadShow = false;
      this.loading = false;
      // 上传成功处理
      if (res) {
        this.uploadShow = false;
        this.$message({
          message: '上传文件成功，等待模型解析...',
          type: 'success',
        });
        console.log(res, '上传文件成功', res.data, res.task_ids[0]);
        // 根据 taskid 开启sse访问
        if (res.task_ids[0]) {
          const controller = new AbortController();
          fetchEventSource('/api/knowledge_base/files/upload_sse/', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json;charset=UTF-8',
              Accept: ['text/event-stream', 'application/json'],
              Authorization: this.headers['Authorization'],
            },
            body: JSON.stringify({
              task_id: res.task_ids[0],
            }),
            openWhenHidden: true,
            signal: controller.signal, //与其相关联的signal属性
            onopen(e) {
              console.log(e, 'SSE在连接打开时被调用');

              // 判断 showLoadingList 中是否存在 task_id  如果存在 就不添加
              let isExist = _this.showLoadingList.some((item) => {
                return item.id == res.task_ids[0];
              });
              if (isExist) {
                return;
              } else {
                _this.showLoadingList.push({
                  id: res.task_ids[0],
                  name: '',
                  text: file.name + ' 开始解析中...',
                });
              }
            },
            onmessage(msg, event) {
              const jsonStr = msg.data;
              const taskObj = JSON.parse(jsonStr);
              if (msg.event === 'completed') {
                _this.showLoadingList.forEach((item, index) => {
                  if (item.id == taskObj.task_id) {
                    _this.showLoadingList.splice(index, 1);
                    _this.uploadTree();
                    // controller.abort();
                  }
                });
              } else if (msg.event === 'waiting') {
                // 通过ID 更新状态
                _this.showLoadingList.forEach((item, index) => {
                  if (item.id == taskObj.task_id) {
                    item.name = taskObj.file_name; //
                    item.text = taskObj.message;
                  }
                });
              }
            },
            onclose(e) {
              // controller.abort();
            },
            onerror(err) {
              console.log('onerror:', err);
              // controller.abort();
              // _this.$message.error("出错了,请稍后刷新重试3");
            },
          });
        }
      } else {
        // 上传失败处理
        this.$message({
          message: res.message,
          type: 'error',
        });
        this.beforeClose();
      }
    },
    //新建目录弹窗
    addFolder(type, index) {
      this.currIndex = type;
      this.addIndex = index;
      this.treeForm.name = '';
      this.addShow = true;
    },
    // 当前目录下的文件列表
    seachTextFile() {
      let searchFileList = [];
      if (this.chatInput) {
        // 将小写转换成大写
        let str = this.chatInput.toUpperCase();

        this.currentFileList.forEach((m) => {
          if (m.name.indexOf(str) != -1) {
            searchFileList.push({ name: m.name, id: m.id });
          } else {
          }
        });

        this.searchFileList = searchFileList;
        this.showSearch = true;
      } else {
        this.showSearch = false;
      }
    },
    //点击一级目录
    levelOneClick(item, index) {
      this.treeData.forEach((ite) => {
        if (ite.collection_name != item.collection_name) {
          ite.show = false;
          if (ite.partitions && ite.partitions.length > 0) {
            ite.partitions.forEach((ite) => {
              ite.show = false;
            });
          }
        } else {
          ite.partitions.forEach((ite) => {
            ite.show = false;
          });
        }
      });
      if (this.levelOneSel != item.collection_name) {
        this.levelOneSel = item.collection_name;
        this.levelTwoSel = '';
      }
      item.show = !item.show;
    },
    //点击二级目录
    levelTwoClick(item) {
      if (this.levelTwoSel != item.partition_name) {
        this.levelTwoSel = item.partition_name;
        this.currentFileList = item.files;
      }
      this.seachTextFile();
      // 清楚筛选
    },
    deleteFile(item) {
      var _this = this;
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteData(`api/knowledge_base/files/${item.id}/`)
            .then(() => {
              _this.$message.success('成功删除');
              _this.uploadTree();
            })
            .catch((err) => {})
            .finally((err) => {
              _this.$message.success('成功删除');
              _this.uploadTree();
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });

      //
    },
    //预览pdf
    previewPdf(id, type, name) {
      this.typeValue = '';
      // 新增逻辑 DOC PDF PPTX EXCEL 调用对应的模版进行加载
      if (name.indexOf('.docx') !== -1) {
        this.typeValue = 5;
        this.src = '/api/knowledge_base/files/preview/' + name;
        // + '/?user_id=' + this.$store.state.user.id
        postData(
          'api/sysmanage/operationlog/',
          { action: '预览文件', description: name },
          'post',
        ).then((res) => {});
        this.preShow = true;
        return;
      } else if (name.indexOf('.xlsx') !== -1) {
        this.typeValue = 6;
        this.src = '/api/knowledge_base/files/preview/' + name;
        postData(
          'api/sysmanage/operationlog/',
          { action: '预览文件', description: name },
          'post',
        ).then((res) => {});
        this.preShow = true;
        return;
      } else if (name.indexOf('.pptx') !== -1) {
        this.typeValue = 8;
        this.src = '/api/knowledge_base/files/preview/' + name;
        postData(
          'api/sysmanage/operationlog/',
          { action: '预览文件', description: name },
          'post',
        ).then((res) => {});
        this.preShow = true;
        return;
      }
      console.log(id, type, name, '1111111111');
      this.typeValue = '';
      if (name.indexOf('.mp4') === -1) {
        this.$message.info('努力加载中，请稍侯...');
        this.waitLoading = true;
        postData('api/knowledge_base/files/preview_file/', { file_id: id }, 'post', {
          responseType: 'blob',
        })
          .then((res) => {
            if (res.type == 'application/pdf') {
              this.typeValue = 1;
              const url = window.URL.createObjectURL(new Blob([res], { type: 'application/pdf' }));
              this.pdfUrl = url;
              this.preShow = true;
            } else if (res.type == 'text/markdown') {
              this.typeValue = 2;
              this.keyValue = 'md' + Math.floor(Math.random() * 1000 + 1);
              const reader = new FileReader();
              reader.onload = (event) => {
                const markdownText = event.target.result;
                // 将 Markdown 转换为 HTML
                this.markdownContent = marked(markdownText);
                this.preShow = true;

                this.$nextTick(() => {
                  this.addLinkClickListeners();
                  // this.waitForImagesToLoad();
                });
              };
              reader.onerror = (error) => {
                console.error('Error reading Blob:', error);
              };
              reader.readAsText(res, 'UTF-8'); // 指定编码为 UTF-8
            } else if (res.type == 'image/png' || res.type == 'image/jpeg') {
              this.typeValue = 3;
              const blob = new Blob([res], { type: res.type }); // 根据实际情况设置 MIME 类型
              // 创建临时的 URL
              this.imageUrl = URL.createObjectURL(blob);
              this.preShow = true;
            }
          })
          .catch((e) => {
            this.$message.error('获取文件失败，请稍后重试或联系管理员...');
          })
          .finally((v) => {
            this.waitLoading = false;
          });
      } else {
        this.getVideoRUrl(id);
        return;
      }
    },
    waitForImagesToLoad() {
      const mdViewer = this.$refs.mdViewer;
      if (!mdViewer) return;

      const images = mdViewer.querySelectorAll('img');
      if (images.length === 0) {
        this._renderWatermark();
        return;
      }

      let loadedCount = 0;
      const totalImages = images.length;

      images.forEach((img) => {
        img.onload = () => {
          loadedCount++;
          if (loadedCount === totalImages) {
            this.imagesLoaded = true;
            this._renderWatermark();
          }
        };

        // Handle images that are already complete
        if (img.complete) {
          loadedCount++;
          if (loadedCount === totalImages) {
            this.imagesLoaded = true;
            this._renderWatermark();
          }
        }
      });
    },
    // 在画布上渲染水印
    _renderWatermark() {
      this.$nextTick(() => {
        let canvas = this.$refs.mdCanvas;
        canvas.width = this.$refs.mdViewer.clientWidth;
        canvas.height = this.$refs.mdViewer.clientHeight;
        let ctx = canvas.getContext('2d');
        // 平铺水印
        let pattern = ctx.createPattern(this._initWatermark(), 'repeat');
        ctx.rect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = pattern;
        ctx.fill();
      });
    },

    // 生成水印图片
    _initWatermark() {
      let canvas = document.createElement('canvas');
      canvas.width = 200;
      canvas.height = 200;
      let ctx = canvas.getContext('2d');
      ctx.rotate((-18 * Math.PI) / 180);
      ctx.font = '30px Vedana';
      ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
      ctx.textAlign = 'left';
      ctx.textBaseline = 'middle';
      ctx.fillText(this.watermark, 10, 100);
      return canvas;
    },
  },
};
</script>

<style lang="scss" scoped>
.fileItem {
  font-size: 14px;
  line-height: 30px;
}
.h2-item {
  color: #fff;
  font-weight: normal;
  font-size: 16px;
  padding: 0;
  margin: 0;
  line-height: 40px;
}
.upload-btn {
  width: calc(100% - 20px);
  margin-left: 10px;
}
.loading-item {
  margin-left: 44px;
}
.page-title {
  color: #5993ff;
  background-color: #e5f3ff;
  line-height: 40px;
  padding: 0 20px;
  font-size: 16px;
}
.loading-contaienr {
  max-height: 100px;
  overflow: auto;
}
.centerFlex {
  display: block;
  padding: 10px;
}
.alert-container {
  display: block;
  width: 100%;
  .btn {
    margin: 20px auto 10px;
    width: 200px;
    display: block;
  }
}
</style>
